package com.gin.kotlin.no_gay_alliance.manager

import android.util.Log
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.database.entity.NgaAccount
import com.gin.kotlin.no_gay_alliance.interceptor.LoggingInterceptor
import com.gin.kotlin.no_gay_alliance.store.GlobalProperty
import com.gin.nga.enums.NgaDomain
import com.gin.nga.main.NgaApi
import java.lang.ref.WeakReference

/**
 * 账号管理器
 */
class AccountManager private constructor() {
    private val dao = App.INSTANCE.database.accountDao()

    /**
     * 初始化，加载当前账号;切换账号、切换域名时需要执行
     */
    fun init() {
        val account = dao.list().firstOrNull { it.enable } ?: NgaAccount()
        Log.d(TAG, "[账号管理器] 初始化: 当前用户: ${account.username}(${account.userId})")

        if (account.userId == 0L) App.INSTANCE.toast("当前未登录账号")
        else App.INSTANCE.toast("当前账号: ${account.username}")

        login(account)
    }

    /**
     * 将指定账号设置为当前账号并登录
     * @param userId Long
     */
    fun setEnableLogin(userId: Long) {
        dao.getByUserId(userId) ?: throw RuntimeException("未找到用户信息: $userId")
        dao.clearEnable()
        dao.setEnable(userId)
        login(userId)
    }

    /**
     * 删除账号
     * @param userId Long
     * @return Int
     */
    fun delete(userId: Long) = dao.delete(userId)


    /**
     * 添加账号
     * @param account NgaAccount
     */
    fun add(account: NgaAccount) = dao.add(account)
    fun add(account: List<NgaAccount>) = dao.add(account)

    /**
     * 查询所有账号
     * @return List<NgaAccount>
     */
    fun list() = dao.list()


    /**
     * 切换域名后执行
     */
    fun onDomainChanged(ngaDomain: NgaDomain) {
        Log.i(TAG, "域名切换: ${ngaDomain.host}")
        // 使用当前域名和账号重新构建api
        App.INSTANCE.ngaApi = NgaApi.Builder(App.INSTANCE.account.toCookie(), ngaDomain)
            .also { it.clientBuilder.addInterceptor(LoggingInterceptor()) }
            .build()
    }

    /**
     * 登录指定账号
     * @param userId 用户ID
     */
    private fun login(userId: Long) {
        login(dao.getByUserId(userId) ?: throw RuntimeException("未找到用户信息: $userId"))
    }

    /**
     * 登录账号：初始化API，将账号和API设置到APP
     * @param account NgaAccount
     */
    private fun login(account: NgaAccount) {
        val ngaApi = NgaApi.Builder(account.toCookie(), GlobalProperty.getInstance().domain)
            .also { it.clientBuilder.addInterceptor(LoggingInterceptor()) }
            .build()

        App.INSTANCE.account = account
        App.INSTANCE.ngaApi = ngaApi
    }

    companion object {
        private val TAG = AccountManager::class.java.simpleName
        private var instance: WeakReference<AccountManager> = WeakReference(AccountManager())

        /**
         * 单例模式+弱引用
         * @return Any
         */
        fun getInstance(): AccountManager = instance.get() ?: AccountManager().also { instance = WeakReference(it) }
    }
}